package com.spice.im.group;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;






























//import com.example.android.bitmapfun.util.AsyncTask;
import com.beem.push.utils.AsyncTask;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.speed.im.login.EncryptionUtil;
import com.spice.im.ContactFrameActivity;
import com.spice.im.FlippingLoadingDialog;
import com.spice.im.OtherProfileActivity;
import com.spice.im.R;
import com.spice.im.SpiceApplication;
import com.spice.im.attendance.AttendanceActivity2;
import com.spice.im.attendance.AttendanceClassSection;
import com.spice.im.chat.MessageAdapter;
import com.spice.im.preference.PreferenceActivity;
import com.spice.im.preference.PreferenceActivity.exPhoneCallListener;
import com.spice.im.ui.HandyTextView;
import com.spice.im.utils.DialogUtil;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.ImageFetcher;
import com.spice.im.utils.MyDialog;
import com.spice.im.utils.MyDialogPopWinGroup;
import com.spice.im.utils.MyDialogPopWinSelect;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;
import com.spice.im.utils.MyDialog.MyDialogListener;
import com.stb.core.chat.ContactGroup;
import com.stb.isharemessage.BeemApplication;
import com.stb.isharemessage.IConnectionStatusCallback;
import com.stb.isharemessage.service.XmppConnectionAdapter;
import com.stb.isharemessage.service.aidl.IXmppFacade;
import com.stb.isharemessage.utils.BeemConnectivity;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

public class GroupDetailsActivity extends Activity implements IConnectionStatusCallback,OnClickListener {//,android.widget.AdapterView.OnItemClickListener
	private static ExecutorService LIMITED_TASK_EXECUTOR;
    static {
      LIMITED_TASK_EXECUTOR = (ExecutorService) Executors.newFixedThreadPool(7); 
    }; 
	private static final Intent SERVICE_INTENT = new Intent();
	static {
		SERVICE_INTENT.setComponent(new ComponentName("com.spice.im", "com.stb.isharemessage.BeemService"));
	}
	private boolean mBinded = false;
    private IXmppFacade mXmppFacade;
    protected FlippingLoadingDialog mLoadingDialog;
    private HeaderLayout mHeaderLayout;
	
    private static final String TAG = "GroupDetailsActivity";
    private final ServiceConnection mServConn = new BeemServiceConnection();
    
    protected List<AsyncTask<Void, Void, Boolean>> mAsyncTasks = new ArrayList<AsyncTask<Void, Void, Boolean>>();
	protected void putAsyncTask(AsyncTask<Void, Void, Boolean> asyncTask) {
		mAsyncTasks.add(asyncTask.executeOnExecutor(LIMITED_TASK_EXECUTOR, null));
	}

	protected void clearAsyncTask() {
		Iterator<AsyncTask<Void, Void, Boolean>> iterator = mAsyncTasks
				.iterator();
		while (iterator.hasNext()) {
			AsyncTask<Void, Void, Boolean> asyncTask = iterator.next();
			if (asyncTask != null && !asyncTask.isCancelled()) {
				asyncTask.cancel(true);
			}
		}
		mAsyncTasks.clear();
	}		    
	protected void showLoadingDialog(String text) {
		if (text != null) {
			mLoadingDialog.setText(text);
		}
		mLoadingDialog.show();
	}

	protected void dismissLoadingDialog() {
		if (mLoadingDialog.isShowing()) {
			mLoadingDialog.dismiss();
		}
	}
    
    private static final int REQUEST_CODE_ADD_USER = 0;
    private static final int REQUEST_CODE_EDIT_GROUPNAME = 5;


    private EaseExpandGridView userGridview;
    private String groupId;
    private String groupName;
    private String tagimg;
    private String invitetag;//0 代表被邀请
//    private EMGroup group;
    private GridAdapter adapter;
    private ProgressDialog progressDialog;

    private RelativeLayout rl_switch_block_groupmsg;
    private RelativeLayout rl_group_qr;

    private TextView tv_group_change_name,num;

    public static GroupDetailsActivity instance;

    String st = "";
    // 清空所有聊天记录
    private RelativeLayout clearAllHistory;
    private RelativeLayout changeGroupNameLayout;
//    private GroupRemoveListener groupRemoveListener;//监测群组解散或者被T事件

    private Button id_exit_group;//退出群组
    private Button id_join_group;//加入群组
//    private Button id_delete_group;//解散群组
    private List<ContactGroup> memberItems,allMemberItems;
    private RelativeLayout deleteRl,exitRl,moreRl;
    private Button deleteBtn;//解散群组
    private ImageView iv_switch_block_groupmsg;
	/**
	 * 关闭屏蔽群消息imageview
	 */
	private ImageView iv_switch_unblock_groupmsg;
	boolean add = true;
	public boolean isInDeleteMode;
	ImageView zhidingo,zhiding;

//	private ImageFetcher mImageFetcher;
	private Context mContext;
    //网络状态start
	private View mNetErrorView;
	private TextView mConnect_status_info;
	private ImageView mConnect_status_btn;
    private exPhoneCallListener myPhoneCallListener = null;
    private TelephonyManager tm = null;
    //网络状态end
	
    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.em_activity_group_details);
        mContext = this;
        instance = this;
        mLoadingDialog = new FlippingLoadingDialog(this, "请求提交中");
        mHeaderLayout = (HeaderLayout) findViewById(R.id.login_header);
        
//        mImageFetcher = new ImageFetcher(this, 240);
//        mImageFetcher.setUListype(0);////0普通图片listview 1瀑布流  2地图模式
//        mImageFetcher.setLoadingImage(R.drawable.empty_photo);
        
        // 获取传过来的groupid
        groupId = getIntent().getStringExtra("groupId");
        groupName = getIntent().getStringExtra("groupName");
        tagimg = getIntent().getStringExtra("tagimg");
        invitetag = getIntent().getStringExtra("invitetag");
        mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
		mHeaderLayout.setTitleRightImageButton("聊天信息", null,
				R.drawable.return2,
				new OnRightImageButtonClickListener());
		
//        showCustomToast("groupId="+groupId+";groupName="+groupName);
//        getGroupMembers(groupId);
//        group = EMClient.getInstance().groupManager().getGroup(groupId);

        // we are not supposed to show the group if we don't find the group
//        if (cGroups.size() == 0) {
//            finish();
//            return;
//        }

        
        st = getResources().getString(R.string.people);
        clearAllHistory = (RelativeLayout) findViewById(R.id.clear_all_history);
        userGridview = (EaseExpandGridView) findViewById(R.id.gridview);
//        userGridview.setOnItemClickListener(this);
//        userGridview.setOnClickListener(this);
        
        changeGroupNameLayout = (RelativeLayout) findViewById(R.id.rl_change_group_name);
        tv_group_change_name = (TextView) findViewById(R.id.tv_group_change_name);
        id_exit_group = (Button) findViewById(R.id.id_exit_group);
        id_join_group = (Button) findViewById(R.id.id_join_group);
//        id_delete_group =  (Button) findViewById(R.id.delete_group);
        if(invitetag!=null
        		&& invitetag.length()!=0
        		&& !invitetag.equalsIgnoreCase("null")
        		&& invitetag.equalsIgnoreCase("0")){
        	id_exit_group.setVisibility(View.GONE);
        	id_join_group.setVisibility(View.VISIBLE);
        }else{
        	id_exit_group.setVisibility(View.VISIBLE);
        	id_join_group.setVisibility(View.GONE);
        }
        rl_switch_block_groupmsg = (RelativeLayout) findViewById(R.id.rl_switch_block_groupmsg);
        rl_group_qr = (RelativeLayout) findViewById(R.id.rl_group_qr);
        iv_switch_block_groupmsg = (ImageView) findViewById(R.id.iv_switch_block_groupmsg);
		iv_switch_unblock_groupmsg = (ImageView) findViewById(R.id.iv_switch_unblock_groupmsg);
		zhidingo = (ImageView) findViewById(R.id.zhiding_o);
		zhiding = (ImageView) findViewById(R.id.zhidingimg);


        deleteRl = (RelativeLayout) findViewById(R.id.delete_rl);
        deleteBtn = (Button) findViewById(R.id.delete_group);
        exitRl = (RelativeLayout) findViewById(R.id.exit_rl);
        moreRl = (RelativeLayout) findViewById(R.id.rl_more);
        num = (TextView) findViewById(R.id.tv_num);

        rl_switch_block_groupmsg.setOnClickListener(this);
        rl_group_qr.setOnClickListener(this);
        deleteBtn.setOnClickListener(this);
        id_join_group.setOnClickListener(this);
        moreRl.setOnClickListener(this);
        zhidingo.setOnClickListener(this);
        zhiding.setOnClickListener(this);
        boolean have = false;
        have = iszhidingAccount(groupId+"@1");
//        if (ConversationListFragment.conversionItems != null && ConversationListFragment.conversionItems.size()>0) {
//			for (int i = 0; i < ConversationListFragment.conversionItems.size(); i++) {
//				if (ConversationListFragment.conversionItems.get(i).getType_id().equals(groupId)) {
//					have = true;
//					break;
//				}
//			}
//		}
        
        if (have) {
			zhidingo.setVisibility(View.VISIBLE);
			zhiding.setVisibility(View.GONE);
		} else {
			zhidingo.setVisibility(View.GONE);
			zhiding.setVisibility(View.VISIBLE);
		}
        
//        if (group.getOwner() == null || "".equals(group.getOwner())
//                || !group.getOwner().equals(EMClient.getInstance().getCurrentUser())) {
//            changeGroupNameLayout.setVisibility(View.GONE);
//            add = false;
//        }
//
////        groupRemoveListener = new GroupRemoveListener();
//        EMClient.getInstance().groupManager().addGroupChangeListener(groupRemoveListener);
//        setTitle(group.getGroupName() + "(" + group.getAffiliationsCount() + st);
//        
//        tv_group_change_name.setText(group.getGroupName());
//
////        List<String> members = new ArrayList<String>();
////        members.addAll(group.getMembers());
        memberItems = new ArrayList<ContactGroup>();
        adapter = new GridAdapter(this, R.layout.em_grid, memberItems);
        userGridview.setAdapter(adapter);
//     // 如果自己是群主，显示解散按钮
//     		if (EMClient.getInstance().getCurrentUser().equals(group.getOwner())) {
//     			exitRl.setVisibility(View.GONE);
//     			deleteRl.setVisibility(View.VISIBLE);
//     		}
//        // 保证每次进详情看到的都是最新的group
//        updateGroup();
        boolean istoggle = false;
        istoggle = istoggleBlockGroup(groupId+"@1");


      // update block
      if (istoggle) {
      	
      	iv_switch_block_groupmsg.setVisibility(View.VISIBLE);
      	iv_switch_unblock_groupmsg.setVisibility(View.INVISIBLE);
      } else {
      	iv_switch_block_groupmsg.setVisibility(View.INVISIBLE);
      	iv_switch_unblock_groupmsg.setVisibility(View.VISIBLE);
      }
        
//
//        // 设置OnTouchListener
////        userGridview.setOnTouchListener(new OnTouchListener() {
////
////            @SuppressLint("ClickableViewAccessibility")
////            @Override
////            public boolean onTouch(View v, MotionEvent event) {
////                switch (event.getAction()) {
////                    case MotionEvent.ACTION_DOWN:
////                        if (adapter.isInDeleteMode) {
////                            adapter.isInDeleteMode = false;
////                            adapter.notifyDataSetChanged();
////                            return true;
////                        }
////                        break;
////                    default:
////                        break;
////                }
////                return false;
////            }
////        });

        clearAllHistory.setOnClickListener(this);
        changeGroupNameLayout.setOnClickListener(this);


        id_exit_group.setOnClickListener(new OnClickListener() {//退出群组

            @Override
            public void onClick(View v) {
                try {
//                    EMClient.getInstance().groupManager().leaveGroup(groupId);
//                	deleteMembersFromGroup(CurrentUid);
//                    finish();
                    
                    
//                    if (ChatActivity.activityInstance != null) {
//                        ChatActivity.activityInstance.finish();
//                    }
                    
                    
                	String st91 = "确认退出群组吗?";
    				dialog2 =null;		
    				dialog2 = DialogUtil.getMyDialog("退出群组",
    								st91,
    								GroupDetailsActivity.this, new MyDialogListener() {
    									
    									@Override
    									public void onPositiveClick(Dialog dialog, View view) {
    										deleteMembersFromGroup(CurrentUid,true);
    									}
    									
    									@Override
    									public void onNegativeClick(Dialog dialog, View view) {
    										
    									}
    								}, MyDialog.ButtonBoth);
    				dialog2.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        
        //网络状态start
        mNetErrorView = findViewById(R.id.net_status_bar_top);
        mConnect_status_info = (TextView)mNetErrorView.findViewById(R.id.net_status_bar_info_top2);
        mConnect_status_btn = (ImageView)mNetErrorView.findViewById(R.id.net_status_bar_btn);
        mConnect_status_btn.setOnClickListener(this);
        
	    IntentFilter mFilter = new IntentFilter();
	    mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
	    registerReceiver(mNetWorkReceiver, mFilter);
        /* 添加自己实现的PhoneStateListener */
        myPhoneCallListener = new exPhoneCallListener();
       
       /* 取得电话服务 */
        tm =(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
       
        /* 注册电话通信Listener */
        tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_CALL_STATE);
	    //网络状态end
        
        BeemApplication.getInstance().addActivity(this);

   //     getGroupMemberInfos();
//        getGroupMembers(groupId);

    }
    @Override
    protected void onResume() {
    	Log.e("================20170507 MainListActivity onResume================", "+++++++onResume+++++++");
		super.onResume();
//		mImageFetcher.setExitTasksEarly(false);
		isWork = false;
		if (!mBinded){
		    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);	    
		}
    }
    
    
    private HashMap cGroups = new HashMap();
    private ArrayList cGroupsList = new ArrayList<ContactGroup>();
    int AffiliationsCount = 0;
    private String OwnerUid = "";
    private String OwnerUsername = "";
    private String CurrentUid = "";
    private String CurrentUsername = "";
    private String CurrentName = "";
    private String CurrentAvatarpath = "";
	private String[] errorMsg = new String[]{"群成员信息获取成功.",
			"服务连接中1-1,请稍候再试.",
			"服务连接中1-2,请稍候再试.",
			"服务连接中1-3,请稍候再试.",
			"网络连接不可用,请检查你的网络设置.",
			"系统错误.群成员信息获取失败.",
			"群成员信息获取失败,hash校验失败"//0002
			};
	private int errorType = 5;
    private boolean initGeGroupMembers(String tagid,String page,String keystr){//page=1 keystr=""
//    	showCustomToast("initGeGroupMembers1");
    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers1111++++++++++++++");
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
				Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers2222++++++++++++++");
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers3333++++++++++++++");
		    	    ViewGroupMemberIQ reqXML = new ViewGroupMemberIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
		            CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		            CurrentName = mXmppFacade.getXmppConnectionAdapter().getName();
		            CurrentAvatarpath = mXmppFacade.getXmppConnectionAdapter().getAvatarpath();
		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		    	    CurrentUsername = username;
//		            reqXML.setUsername(username);
		            reqXML.setTagid(tagid);
		            reqXML.setPage(page);
		            reqXML.setKeystr(keystr);
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
		            reqXML.setUuid(uuid);
	//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "viewgroupmemberiq"; 
		    		String namespace = "com:isharemessage:viewgroupmemberiq";
		    		ViewGroupMemberIQResponseProvider provider = new ViewGroupMemberIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "viewgroupmemberiq", "com:isharemessage:viewgroupmemberiq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof ViewGroupMemberIQResponse) {
		                	final ViewGroupMemberIQResponse viewGroupMemberIQResponse = (ViewGroupMemberIQResponse) rt;
	
		                    if (viewGroupMemberIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:viewgroupmemberiq")) {
	//	    					MainActivity.this.runOnUiThread(new Runnable() {
	//		                    	
	//    							@Override
	//    							public void run() {
	//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
	//    							}
	//    						});
		                        String Id = viewGroupMemberIQResponse.getId();
		                        String Apikey = viewGroupMemberIQResponse.getApikey();
		                        cGroups = viewGroupMemberIQResponse.getCGroups();
		                        AffiliationsCount = cGroups.size();
		                        if(cGroups.size()!=0){
			                        Log.e("响应packet结果解析...............", "Id="+Id+";Apikey="+Apikey); 
//			                        return true;
			                        Iterator iter = cGroups.entrySet().iterator();
			            			Map.Entry entry = null;
			            			Object key = null;
			            			Object val = null;
			            			ContactGroup cGroup = null;
			            			int idx = -1;
			            			String tmp = null;
			            			while (iter.hasNext()) {
			                			entry = (Map.Entry) iter.next();
			                			key = entry.getKey();
			                			val = entry.getValue();
			                			cGroup = (ContactGroup)val;
			                			cGroupsList.add(cGroup);
			                			//isfriend=true;2@0/allen
			                			System.out.println("al_rec.size()="+cGroups.size()+"uid-isfriend="+key+";"+cGroup.getUid()+"@0/"+cGroup.getUsername());
			                			//key的格式：value.get("isfriend")+""+p+"-"+value.get("ownerid")
			                			//isfriend为true或false , p为0自增长数， ownerid为群组用户user_id
//			                			if(((String)key).indexOf("0")!=-1){
//			                				OwnerUid = cGroup.getUid();
//			                				OwnerUsername = cGroup.getUsername();
////			                				break;
//			                			}
			                			idx = ((String)key).indexOf("-");
			                			tmp = ((String)key).substring(idx+1);
			                			if(tmp!=null
			                					&& tmp.length()!=0
			                					&& !tmp.equalsIgnoreCase("null"))
			                				OwnerUid = tmp;
			                			if(OwnerUid.equalsIgnoreCase(cGroup.getUid())){
			                				OwnerUsername = cGroup.getUsername();
//			                				break;
			                			}
			            			}
		                        }
		                        String retcode = viewGroupMemberIQResponse.getRetcode();
		                        String memo = viewGroupMemberIQResponse.getMemo();
		                        if(retcode.equalsIgnoreCase("0000")){
		                        	errorType = 0;
		                        	return true;
		                        }
		                        else if(retcode.equalsIgnoreCase("0002"))
		                        	errorType = 6;
		                        else
		                        	errorType = 5;
		                        
		                    }
		                } 
		            }
		    		errorType = 1;

		    }else
		    	errorType = 1;
		    
			}else
				errorType = 4;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
		}
		return false;
    }
    
    private boolean initConfirm2JoinGroup(String tagid){//page=1 keystr=""
//    	showCustomToast("initGeGroupMembers1");
    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers1111++++++++++++++");
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
				Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers2222++++++++++++++");
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers3333++++++++++++++");
		    	    MucInviteConfirmIQ reqXML = new MucInviteConfirmIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
		            CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		            CurrentName = mXmppFacade.getXmppConnectionAdapter().getName();
		            CurrentAvatarpath = mXmppFacade.getXmppConnectionAdapter().getAvatarpath();
		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		    	    CurrentUsername = username;
		            reqXML.setUsername(username);
		            reqXML.setTagid(tagid);
		            reqXML.setR("1");//用户确认加入r=1或拒绝加入r=0群组
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
		            reqXML.setUuid(uuid);
	//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid+tagid;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "mucinviteconfirmiq"; 
		    		String namespace = "com:isharemessage:mucinviteconfirmiq";
		    		MucInviteConfirmIQProvider provider = new MucInviteConfirmIQProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "mucinviteconfirmiq", "com:isharemessage:mucinviteconfirmiq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof MucInviteConfirmIQResponse) {
		                	final MucInviteConfirmIQResponse mucInviteConfirmIQResponse = (MucInviteConfirmIQResponse) rt;
	
		                    if (mucInviteConfirmIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:mucinviteconfirmiq")) {
	//	    					MainActivity.this.runOnUiThread(new Runnable() {
	//		                    	
	//    							@Override
	//    							public void run() {
	//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
	//    							}
	//    						});
		                        String Id = mucInviteConfirmIQResponse.getId();
		                        String Apikey = mucInviteConfirmIQResponse.getApikey();
		                        String retcode = mucInviteConfirmIQResponse.getRetcode();
		                        String memo = mucInviteConfirmIQResponse.getMemo();
		                        if(retcode.equalsIgnoreCase("0000")){
		                        	errorType = 0;
		                        	return true;
		                        }
		                        else if(retcode.equalsIgnoreCase("0002"))
		                        	errorType = 6;
		                        else
		                        	errorType = 5;
		                        
		                    }
		                } 
		            }
		    		errorType = 1;

		    }else
		    	errorType = 1;
		    
			}else
				errorType = 4;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
		}
		return false;
    }
    
    public boolean addUsersToGroup(String tagid,String ids){
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    		MucInviteIQ reqXML = new MucInviteIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
		            CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		            CurrentName = mXmppFacade.getXmppConnectionAdapter().getName();
		            CurrentAvatarpath = mXmppFacade.getXmppConnectionAdapter().getAvatarpath();
		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		    	    CurrentUsername = username;
		            reqXML.setUsername(username);
		            reqXML.setTagid(tagid);
		            reqXML.setTagname(groupName);
		            reqXML.setTagimg(tagimg);
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
		            reqXML.setUuid(uuid);
		            reqXML.setIds(ids);
	//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid+tagid;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "mucinviteiq"; 
		    		String namespace = "com:isharemessage:mucinviteiq";
		    		MucInviteIQResponseProvider provider = new MucInviteIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "mucinviteiq", "com:isharemessage:mucinviteiq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof MucInviteIQResponse) {
		                	final MucInviteIQResponse mucInviteIQResponse = (MucInviteIQResponse) rt;
	
		                    if (mucInviteIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:mucinviteiq")) {
	//	    					MainActivity.this.runOnUiThread(new Runnable() {
	//		                    	
	//    							@Override
	//    							public void run() {
	//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
	//    							}
	//    						});
		                        String Id = mucInviteIQResponse.getId();
		                        String Apikey = mucInviteIQResponse.getApikey();
		                        String retcode = mucInviteIQResponse.getRetcode();
		                        String memo = mucInviteIQResponse.getMemo();
		                        if(retcode.equalsIgnoreCase("0000")){
		                        	return true;
		                        }
		                        else if(retcode.equalsIgnoreCase("0002")){
		                        	errorType = 6;
		                        	return false;
		                        }else{
		                        	errorType = 5;
		                        	return false;
		                        }
		                    }
		                } 
		            }
		    		errorType = 1;
		            return false;

		    }else
		    	errorType = 1;
		    	return false;
			}else
				errorType = 4;
				return false;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
			return false;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
			return false;
		}
//		return false;
    }
    
    private boolean flag = false;
	private boolean isWork = false;
	private void getGroupMembers(final String tagid) {
//		showCustomToast("getGroupMembers1");
		Log.e("================GroupDetailsActivity.java ================", "++++++++++++++getGroupMembers111++++++++++++++");
		if(!isWork){
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showLoadingDialog("正在加载,请稍后...");
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				cGroupsList.clear();//清除上次记录
				return initGeGroupMembers(tagid,"1","");
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				dismissLoadingDialog();
				if (result) {	
					mHandler.sendEmptyMessage(1);
				}else{
					//提示没有获取到数据：可能网络问题
					mHandler.sendEmptyMessage(0);
				}
				flag = false;
				isWork = false;
			}

		});
		isWork = true;
		}
	}
	
	private void Confirm2JoinGroup(final String tagid) {
//		showCustomToast("getGroupMembers1");
		Log.e("================GroupDetailsActivity.java ================", "++++++++++++++getGroupMembers111++++++++++++++");
		if(!isWork){
		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showLoadingDialog("正在加载,请稍后...");
			}

			@Override
			protected Boolean doInBackground(Void... params) {
//				cGroupsList.clear();//清除上次记录
				return initConfirm2JoinGroup(tagid);
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
				dismissLoadingDialog();
//				if (result) {	
					mHandler.sendEmptyMessage(2);
//				}else{
//					//提示没有获取到数据：可能网络问题
//					mHandler.sendEmptyMessage(3);
//				}
				flag = false;
				isWork = false;
			}

		});
		isWork = true;
		}
	}
	private Handler mHandler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case 0:
//			        if (cGroups.size() == 0) {
//			            finish();
//			            return;
//			        }
					break;
				case 1:
//					if (OwnerUid == null 
//					        || "".equals(OwnerUid)
//					        || OwnerUid.length() == 0
//			                || !OwnerUid.equals(CurrentUid)) {
//			            changeGroupNameLayout.setVisibility(View.GONE);
//			            add = false;
//			        }
		
		//	        groupRemoveListener = new GroupRemoveListener();
//			        EMClient.getInstance().groupManager().addGroupChangeListener(groupRemoveListener);
			        setTitle(groupName + "(" + AffiliationsCount + st);
			        
			        tv_group_change_name.setText(groupName);
			        num.setText(AffiliationsCount+"");//+";cuid="+CurrentUid+";owid="+OwnerUid
		//	        List<String> members = new ArrayList<String>();
		//	        members.addAll(group.getMembers());
//			        memberItems = new ArrayList<ContactGroup>();
//			        adapter = new GridAdapter(GroupDetailsActivity.this, R.layout.em_grid, memberItems);
//			        userGridview.setAdapter(adapter);
			     // 如果自己是群主，显示解散按钮
			     		if (CurrentUid.equals(OwnerUid)) {
			     			exitRl.setVisibility(View.GONE);
			     			deleteRl.setVisibility(View.VISIBLE);
			     		}
			        // 保证每次进详情看到的都是最新的group
//			        updateGroup();
	        
					memberItems.clear();
                    if (allMemberItems == null) {
						allMemberItems = new ArrayList<ContactGroup>();
					}
                    allMemberItems.clear();
                    allMemberItems.addAll(cGroupsList);
                    if (AffiliationsCount<=15) {
                    	memberItems.addAll(cGroupsList);
                    	moreRl.setVisibility(View.GONE);
					} else {
						for (int i = 0; i < 15; i++) {
							memberItems.add((ContactGroup)cGroupsList.get(i));
							moreRl.setVisibility(View.VISIBLE);
						}
					}
                    
                    adapter = null;
                    adapter = new GridAdapter(GroupDetailsActivity.this, R.layout.em_grid, memberItems);
                    userGridview.setAdapter(adapter);
					break;
				case 2:
					showCustomToast("处理完成!");
					startActivity(new Intent(GroupDetailsActivity.this, ContactFrameActivity.class));//ContactListPullRefListActivity
					finish();	
					break;
				case 3:
					if(errorType!=5)
						showCustomToast(errorMsg[errorType]);
					break;
				case 5:
					showCustomToast("群组信息更新成功!");
					dialog3.dismiss();
					break;
				default:
					break;
			}
		}
	};
    

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(dialog3!=null)
        ((MyDialogPopWinGroup)dialog3).onActivityResult(requestCode, resultCode, data);
        
        String st1 = getResources().getString(R.string.being_added);
        String st2 = getResources().getString(R.string.is_quit_the_group_chat);
        String st3 = getResources().getString(R.string.chatting_is_dissolution);
        String st4 = getResources().getString(R.string.are_empty_group_of_news);
        String st5 = getResources().getString(R.string.is_modify_the_group_name);
        final String st6 = getResources().getString(R.string.Modify_the_group_name_successful);
        final String st7 = getResources().getString(R.string.change_the_group_name_failed_please);

        if (resultCode == RESULT_OK) {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(GroupDetailsActivity.this);
                progressDialog.setMessage(st1);
                progressDialog.setCanceledOnTouchOutside(false);
            }
            switch (requestCode) {
                case REQUEST_CODE_ADD_USER:// 添加群成员
//                    final String[] newmembers = data.getStringArrayExtra("newmembers");
//                    /
                    final List<ContactGroup> friends_cGroup_select = (List<ContactGroup>)data.getSerializableExtra("newmembers");
                    progressDialog.setMessage(st1);
                    progressDialog.show();
                    addMembersToGroup(friends_cGroup_select);
                    break;

                case REQUEST_CODE_EDIT_GROUPNAME: //修改群名称
                    final String returnData = data.getStringExtra("data");
                    if (!TextUtils.isEmpty(returnData)) {
                        progressDialog.setMessage(st5);
                        progressDialog.show();

                        new Thread(new Runnable() {
                            public void run() {
                                try {
//                                    EMClient.getInstance().groupManager().changeGroupName(groupId, returnData);
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            setTitle(returnData + "(" + AffiliationsCount
                                                    + st);
                                            tv_group_change_name.setText(returnData);
                                            progressDialog.dismiss();
                                            Toast.makeText(getApplicationContext(), st6, Toast.LENGTH_SHORT).show();
                                        }
                                    });

                                } catch (Exception e) {
                                    e.printStackTrace();
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            progressDialog.dismiss();
                                            Toast.makeText(getApplicationContext(), st7, Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                }
                            }
                        }).start();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    protected void addUserToBlackList(final String username) {
        final ProgressDialog pd = new ProgressDialog(this);
        pd.setCanceledOnTouchOutside(false);
        pd.setMessage(getString(R.string.Are_moving_to_blacklist));
        pd.show();
        new Thread(new Runnable() {
            public void run() {
                try {
//                    EMClient.getInstance().groupManager().blockUser(groupId, username);
                    runOnUiThread(new Runnable() {
                        public void run() {
//                            refreshMembers(group);
                        	getGroupMembers(groupId);
                            pd.dismiss();
                            Toast.makeText(getApplicationContext(), R.string.Move_into_blacklist_success, Toast.LENGTH_SHORT).show();
                        }
                    });
                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            pd.dismiss();
                            Toast.makeText(getApplicationContext(), R.string.failed_to_move_into, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }).start();
    }

//    private void refreshMembers(EMGroup group) {
////        adapter.clear();
//
//        //TODO
////        List<String> members = new ArrayList<String>();
////        members.addAll(group.getMembers());
////        adapter.addAll(members);
//
//        if (!isFinishing()) {
//            getGroupMemberInfos(group);
//        }
//
////        adapter.notifyDataSetChanged();
//    }


    /**
     * 清空群聊天记录
     */
    private void clearGroupHistory1() {

//        EMClient.getInstance().chatManager().deleteConversation(group.getGroupId(), true);
//        handler.obtainMessage(StringConfig.SHOW_TOAST, "群消息已被清空").sendToTarget();
    	MessageAdapter messageAdapter = MessageAdapter.getInstance(mContext);
    	messageAdapter.deleteMessages(groupId+"@1",CurrentUid);//parseBareAddress
    }
	protected void clearGroupHistory() {
		String st9 = getResources().getString(R.string.sure_to_empty_this);
		final String st13 = getResources().getString(R.string.success);
        final String st14 = getResources().getString(R.string.Delete_failed);
        final ProgressDialog deleteDialog = new ProgressDialog(GroupDetailsActivity.this);
        deleteDialog.setMessage(st9);
        deleteDialog.setCanceledOnTouchOutside(false);
        deleteDialog.show();
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    // 删除被选中的成员
//					EMClient.getInstance().groupManager().removeUserFromGroup(idString, username);
                	MessageAdapter messageAdapter = MessageAdapter.getInstance(mContext);
                	messageAdapter.deleteMessages(groupId+"@1",CurrentUid);//parseBareAddress
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            deleteDialog.dismiss();
                            Toast.makeText(getApplicationContext(), "清空群聊天记录成功.", Toast.LENGTH_LONG).show();
                        }
                    });
                } catch (final Exception e) {
                    deleteDialog.dismiss();
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(getApplicationContext(), st14 + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }

            }
        }).start();
    }
    /**
     * 增加群成员
     *
     * @param newmembers
     */
    private boolean bol_muninvite = false;
    private void addMembersToGroup(final List<ContactGroup> newmembers) {
        final String st6 = getResources().getString(R.string.Add_group_members_fail);
        new Thread(new Runnable() {

            public void run() {
                try {
                    // 创建者调用add方法
                    if (CurrentUid.equals(OwnerUid)) {
//                        EMClient.getInstance().groupManager().addUsersToGroup(groupId, newmembers);
                    	if(newmembers!=null
                    			&& newmembers.size()!=0){
                    		String ids = "";
                    		ContactGroup di;
                    		for(int i=0;i<newmembers.size()-1;i++){
                    			di = (ContactGroup)newmembers.get(i);
                    			if(di.getJID().indexOf("@0/")!=-1)
                    			ids += di.getJID().replace("@0/", "|") + ",";
                    		}
                    		di = (ContactGroup)newmembers.get(newmembers.size()-1);
                    		if(di.getJID().indexOf("@0/")!=-1)
                    		ids += di.getJID().replace("@0/", "|") ;
                    		bol_muninvite = addUsersToGroup(groupId,ids);
                    	}
                    } else {
                        // 一般成员调用invite方法
//                        EMClient.getInstance().groupManager().inviteUser(groupId, newmembers, null);
                    	if(newmembers!=null
                    			&& newmembers.size()!=0){
                    		String ids = "";
                    		ContactGroup di;
                    		for(int i=0;i<newmembers.size()-1;i++){
                    			di = (ContactGroup)newmembers.get(i);
                    			ids += di.getJID().replace("@0/", "|") + ",";
                    		}
                    		di = (ContactGroup)newmembers.get(newmembers.size()-1);
                    		ids += di.getJID().replace("@0/", "|") ;
                    		bol_muninvite = addUsersToGroup(groupId,ids);
                    	}
                    }
                    runOnUiThread(new Runnable() {
                        public void run() {
//                            refreshMembers(group);
                        	if(bol_muninvite)
                        		showCustomToast("群组邀请消息已成功发送!");
                        	else
                        		showCustomToast("群组邀请失败!"+errorMsg[errorType]);
                        	getGroupMembers(groupId);		
                            setTitle(groupName + "(" + AffiliationsCount + st);
                            progressDialog.dismiss();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), st6 + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }
    
    public boolean iszhidingAccount(String barejid) {//uid或tagid@0或1
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		String zhiding_username = settings.getString(SpiceApplication.ZHIDING_ACCOUNT_USERNAME_KEY, "");
//		showCustomToast("置顶"+zhiding_username); 
		int idx = zhiding_username.indexOf(barejid);
		if(idx!=-1){
			return true;
		}
		return false;
    }
    
    public void zhidingAccount(String barejid) {//uid或tagid@0或1
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		String zhiding_username = settings.getString(SpiceApplication.ZHIDING_ACCOUNT_USERNAME_KEY, "");
		SharedPreferences.Editor edit = settings.edit();
		//String[] arr = zhiding_username.split("#");
		int idx = zhiding_username.indexOf(barejid);
		if(idx==-1){
			zhiding_username += "#"+barejid;
			edit.putString(SpiceApplication.ZHIDING_ACCOUNT_USERNAME_KEY, zhiding_username);
			edit.commit();
		}
    }
    public void cancelzhidingAccount(String barejid) {//uid或tagid@0或1
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		String zhiding_username = settings.getString(SpiceApplication.ZHIDING_ACCOUNT_USERNAME_KEY, "");
		SharedPreferences.Editor edit = settings.edit();
		int idx = zhiding_username.indexOf(barejid);
//		showCustomToast("取消置顶000="+idx);
		if(idx!=-1){
			zhiding_username = zhiding_username.replace("#"+barejid, "");
			edit.putString(SpiceApplication.ZHIDING_ACCOUNT_USERNAME_KEY, zhiding_username);
			edit.commit();
		}
    }
    
    Dialog dialog2,dialog3;
    String procinsid;
    @Override
    public void onClick(View v) {
//    	RequestMap map;
        switch (v.getId()) {
			//网络设置
	        case R.id.net_status_bar_btn:
				setNetworkMethod(this);
			break;
            case R.id.rl_switch_block_groupmsg: // 屏蔽或取消屏蔽群组
            	if (iv_switch_block_groupmsg.getVisibility() == View.VISIBLE) {
            		toggleBlockGroup(false);
    			} else {
    				toggleBlockGroup(true);
    			}
                break;

            case R.id.clear_all_history: // 清空聊天记录
//                String st9 = getResources().getString(R.string.sure_to_empty_this);
//                new EaseAlertDialog(GroupDetailsActivity.this, null, st9, null, new AlertDialogUser() {
//
//                    @Override
//                    public void onResult(boolean confirmed, Bundle bundle) {
//                        if (confirmed) {
//                            clearGroupHistory();
//                        }
//                    }
//                }, true).show();
            	String st9 = getResources().getString(R.string.sure_to_empty_this);
				dialog2 =null;		
				dialog2 = DialogUtil.getMyDialog("清空聊天记录",
								st9,
								GroupDetailsActivity.this, new MyDialogListener() {
									
									@Override
									public void onPositiveClick(Dialog dialog, View view) {
										clearGroupHistory();
									}
									
									@Override
									public void onNegativeClick(Dialog dialog, View view) {
										
									}
								}, MyDialog.ButtonBoth);
				dialog2.show();

                break;

            case R.id.rl_change_group_name:
//                dataBundle = new Bundle();
//                dataBundle.putString("title", "修改群名称");
//                dataBundle.putString("data", group.getGroupName());
//                baseStartActivityForResult(CommonEditActivity.class, REQUEST_CODE_EDIT_GROUPNAME);
//                //	startActivityForResult(new Intent(this, EditActivity.class).putExtra("data", group.getGroupName()), REQUEST_CODE_EDIT_GROUPNAME);
                
            	
				Date dNow2 = new Date();   //当前时间
        	    SimpleDateFormat sdf2=new SimpleDateFormat("yyyyMMddhhmmss"); //设置时间格式
		    	String defaultStartDate2 = sdf2.format(dNow2);    //格式化前3月的时间
				procinsid = defaultStartDate2+".jpg";
				
            	
				if(dialog3!=null)
					dialog3.dismiss();
				dialog3 =null;		
				dialog3 = DialogUtil.getMyDialogPopWinGroup("修改群信息",
								"",//请选择考勤班段
								GroupDetailsActivity.this, new MyDialogPopWinGroup.MyDialogListener() {
									
									@Override
									public void onPositiveClick(Dialog dialog, View view) {
										String groupName2 = "";
										String photo = "";
										String photoName = "";
										String photo_temp = "";
										if(((MyDialogPopWinGroup)dialog3).getGroupName()!=null 
												&& ((MyDialogPopWinGroup)dialog3).getGroupName().length()!=0
												&& !((MyDialogPopWinGroup)dialog3).getGroupName().equalsIgnoreCase("null")){
											groupName2 = ((MyDialogPopWinGroup)dialog3).getGroupName();
											//UPLoadHeadPath+uid+"/images/photo/"
											photoName = ((MyDialogPopWinGroup)dialog3).getPhotoName();
											
											
//											if(photoName.startsWith("http://"))//原来就有群组图像未修改直接返回来
//												photo = photoName;
//											else//修改成了新的群组图像
////												photo = XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+"/jeesiteoa/userfiles/"+CurrentUid+"/images/photo/"+photoName;
//											photo = XmppConnectionAdapter.downloadPrefix+"/userfiles/"+CurrentUid+"/images/photo/"+photoName;
//											//为了保证存入数据库jchome_mtag表中pic字段不带http前端包括webapp站点
//											//http://10.0.2.2:8080/jeesiteoa/userfiles/57/images/photo/IMG20200313100235.jpg
//											///userfiles/57/images/photo/IMG20200313100235.jpg
//											photo_temp = photo.substring(XmppConnectionAdapter.downloadPrefix.length());
////											startUpdateGroup(groupId,groupName2,photo);
//											startUpdateGroup(groupId,groupName2,photo_temp);
											
											if(photoName.startsWith("http://")){
												photo = photoName;
												photo_temp = photo.substring(XmppConnectionAdapter.downloadPrefix.length());
												tagimg = photo_temp;
											}else{
												photo = photoName;
//												photo_temp = photo;
												photo_temp = "/userfiles/"+CurrentUid+"/images/photo/"+photoName;
												tagimg = photo_temp;
											}
											startUpdateGroup(groupId,groupName2,photo_temp);
											
										}else{
											
												showCustomToast("群组名称不能为空!");
												return;
										}
											//Toast.makeText(GroupDetailsActivity.this, "PositiveClick!photo="+photo, Toast.LENGTH_SHORT).show();
											
										
									}
									
									@Override
									public void onNegativeClick(Dialog dialog, View view) {

//											Toast.makeText(GroupDetailsActivity.this, "NegativeClick!", Toast.LENGTH_SHORT).show();
											dialog3.dismiss();
										
									}
								}, MyDialog.ButtonBoth,CurrentUid,procinsid,groupName,tagimg);
				dialog3.show();
				
				
            	break;
            case R.id.rl_group_qr://二维码
//                dataBundle = new Bundle();
//                dataBundle.putString("title", group.getGroupName());
//                dataBundle.putString("qrcode", groupId);
//                baseStartActivity(GroupQRCodeActivity.class, false);
                break;
                
            case R.id.delete_group://解散群组
            	
            	String st90 = "确认解散群组吗?";
				dialog2 =null;		
				dialog2 = DialogUtil.getMyDialog("解散群组",
								st90,
								GroupDetailsActivity.this, new MyDialogListener() {
									
									@Override
									public void onPositiveClick(Dialog dialog, View view) {
										String st3 = getResources().getString(R.string.chatting_is_dissolution);
						            	progressDialog = new ProgressDialog(GroupDetailsActivity.this);
						                progressDialog.setCanceledOnTouchOutside(false);
						            	progressDialog.setMessage(st3);
										progressDialog.show();
						            	deleteGrop();
									}
									
									@Override
									public void onNegativeClick(Dialog dialog, View view) {
										
									}
								}, MyDialog.ButtonBoth);
				dialog2.show();
				
//            	String st3 = getResources().getString(R.string.chatting_is_dissolution);
//            	progressDialog = new ProgressDialog(GroupDetailsActivity.this);
//                progressDialog.setCanceledOnTouchOutside(false);
//            	progressDialog.setMessage(st3);
//				progressDialog.show();
//            	deleteGrop();
                break;
            case R.id.id_join_group://确认加入群组
            	Confirm2JoinGroup(groupId);
            	break;
                
            case R.id.rl_more:
            	Intent intent = new Intent(GroupDetailsActivity.this, GroupMemberActivity.class);
            	intent.putExtra("add", add);
            	intent.putExtra("id", groupId);
            	intent.putExtra("CurrentName", CurrentName);
            	intent.putExtra("CurrentAvatarpath", CurrentAvatarpath);
            	intent.putExtra("OwnerUid", OwnerUid);
            	if (allMemberItems != null) {
            		intent.putExtra("member", (Serializable)allMemberItems);
				}
            	
            	startActivity(intent);
                break;
                
             case R.id.zhidingimg:

//             	map=new RequestMap();
//     			map.put("type", "1");
//     			map.put("uid", UserManager.getInstance().getUser().getUid());
//     			map.put("type_id", groupId);
//     			RequestServerManager.asyncRequest(0, new RequestByCommonFormat(GroupDetailsActivity.this, map,"置顶中...", UrlConfig.add_conversion_url, new RequestFinishCallback<RequestResult>() {
//
//     				@Override
//     				public void onFinish(RequestResult result) {
//     					// TODO Auto-generated method stub
//     					if (result.isSucceed()) {
//     						if (ConversationListFragment.conversionItems == null) {
//     							ConversationListFragment.conversionItems = new ArrayList<ConversionItem>();
//     						}
//     						ConversionItem conversionItem = new ConversionItem();
//     						conversionItem.setType_id(groupId);
//     						conversionItem.setType("1");
//     						ConversationListFragment.conversionItems.add(conversionItem);
//     					} else {
//                            Toast.makeText(GroupDetailsActivity.this, result.getDescription(), Toast.LENGTH_SHORT).show();
//                        }
//     					zhidingo.setVisibility(View.VISIBLE);
//     					zhiding.setVisibility(View.GONE);
//
//     					
//     				}
//     			}));
            	 
            	zhidingAccount(groupId+"@1");
            	showCustomToast("置顶成功!");   
            	zhidingo.setVisibility(View.VISIBLE);
				zhiding.setVisibility(View.GONE);
     			break;
     			
             case R.id.zhiding_o:


//             	map=new RequestMap();
//             	map.put("uid", UserManager.getInstance().getUser().getUid());
//     			map.put("type", "1");
//     			map.put("type_id", groupId);
//     			RequestServerManager.asyncRequest(0, new RequestByCommonFormat(GroupDetailsActivity.this, map,"取消置顶中...", UrlConfig.del_conversion_url, new RequestFinishCallback<RequestResult>() {
//
//     				@Override
//     				public void onFinish(RequestResult result) {
//     					// TODO Auto-generated method stub
//     					if (result.isSucceed()) {
//     						if (ConversationListFragment.conversionItems != null) {
//     							for (int i = 0; i < ConversationListFragment.conversionItems.size(); i++) {
//     								if (ConversationListFragment.conversionItems.get(i).getType_id().equals(groupId)) {
//     									ConversationListFragment.conversionItems.remove(i);
//     									break;
//     								}
//     							}
//     						}
//     					} else {
//                            Toast.makeText(GroupDetailsActivity.this, result.getDescription(), Toast.LENGTH_SHORT).show();
//                        }
//     					zhidingo.setVisibility(View.GONE);
//     					zhiding.setVisibility(View.VISIBLE);
//     					
//     				}
//     			}));
            	cancelzhidingAccount(groupId+"@1"); 
            	showCustomToast("取消置顶成功!");
            	zhidingo.setVisibility(View.GONE);
				zhiding.setVisibility(View.VISIBLE);        
                         
      			break;
//            case R.id.gridview:
//            	Toast.makeText(this, "333当为删除状态时，单击空白区域，回到正常状态", Toast.LENGTH_SHORT).show();
//            	break;
            default:
                break;
        }

    }
    
    /**
	 * 解散群组
	 *
	 */
	private void deleteGrop() {
		final String st5 = getResources().getString(R.string.Dissolve_group_chat_tofail);
		new Thread(new Runnable() {
			public void run() {
				try {
//                    EMClient.getInstance().groupManager().destroyGroup(groupId);
					initDisMissGroup(groupId);
					runOnUiThread(new Runnable() {
						public void run() {
							progressDialog.dismiss();
							setResult(RESULT_OK);
							startActivity(new Intent(GroupDetailsActivity.this, ContactFrameActivity.class));
							finish();
//							if(ChatActivity.activityInstance != null)
//							    ChatActivity.activityInstance.finish();
						}
					});
				} catch (final Exception e) {
					runOnUiThread(new Runnable() {
						public void run() {
							progressDialog.dismiss();
							Toast.makeText(getApplicationContext(), st5 + e.getMessage(), Toast.LENGTH_LONG).show();
						}
					});
				}
			}
		}).start();
	}
	
    public boolean istoggleBlockGroup(String barejid) {//uid或tagid@0或1
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		String zhiding_username = settings.getString(BeemApplication.DONT_DISTURB_CHAT_NOTIFICATION, "");
//		showCustomToast("置顶"+zhiding_username); 
		int idx = zhiding_username.indexOf(barejid);
		if(idx!=-1){
			return true;
		}
		return false;
    }
    
    public void nowtoggleBlockGroup(String barejid) {//uid或tagid@0或1
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		String zhiding_username = settings.getString(BeemApplication.DONT_DISTURB_CHAT_NOTIFICATION, "");
		SharedPreferences.Editor edit = settings.edit();
		//String[] arr = zhiding_username.split("#");
		int idx = zhiding_username.indexOf(barejid);
		if(idx==-1){
			zhiding_username += "#"+barejid;
			edit.putString(BeemApplication.DONT_DISTURB_CHAT_NOTIFICATION, zhiding_username);
			edit.commit();
		}
    }
    public void canceltoggleBlockGroup(String barejid) {//uid或tagid@0或1
		SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		String zhiding_username = settings.getString(BeemApplication.DONT_DISTURB_CHAT_NOTIFICATION, "");
		SharedPreferences.Editor edit = settings.edit();
		int idx = zhiding_username.indexOf(barejid);
//		showCustomToast("取消置顶000="+idx);
		if(idx!=-1){
			zhiding_username = zhiding_username.replace("#"+barejid, "");
			edit.putString(BeemApplication.DONT_DISTURB_CHAT_NOTIFICATION, zhiding_username);
			edit.commit();
		}
    }








    private void toggleBlockGroup(boolean isOn) {
        if (isOn) {
//            EMLog.d(TAG, "change to unblock group msg");
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(GroupDetailsActivity.this);
                progressDialog.setCanceledOnTouchOutside(false);
            }
            progressDialog.setMessage(getString(R.string.Is_unblock));
            progressDialog.show();
            new Thread(new Runnable() {
                public void run() {
                    try {
                        if (OwnerUid.equals(CurrentUid)) {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    progressDialog.dismiss();
                                    Toast.makeText(getApplicationContext(), "你是群主，不能屏蔽群消息", Toast.LENGTH_LONG).show();
                                }
                            });

                            return;
                        }
//                        EMClient.getInstance().groupManager().blockGroupMessage(groupId);
                        nowtoggleBlockGroup(groupId+"@1");
                        runOnUiThread(new Runnable() {
                            public void run() {
                            	Toast.makeText(getApplicationContext(), "屏蔽群消息成功", Toast.LENGTH_LONG).show();
                            	iv_switch_block_groupmsg.setVisibility(View.VISIBLE);
                            	iv_switch_unblock_groupmsg.setVisibility(View.INVISIBLE);
                                progressDialog.dismiss();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            public void run() {
                                progressDialog.dismiss();
                                Toast.makeText(getApplicationContext(), R.string.remove_group_of, Toast.LENGTH_LONG).show();
                            }
                        });

                    }
                }
            }).start();

        } else {
            String st8 = getResources().getString(R.string.group_is_blocked);
            final String st9 = getResources().getString(R.string.group_of_shielding);
//            EMLog.d(TAG, "change to block group msg");
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(GroupDetailsActivity.this);
                progressDialog.setCanceledOnTouchOutside(false);
            }
            progressDialog.setMessage(st8);
            progressDialog.show();
            new Thread(new Runnable() {
                public void run() {
                    try {

                        if (OwnerUid.equals(CurrentUid)) {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    progressDialog.dismiss();
                                    Toast.makeText(getApplicationContext(), "你是群主，不能屏蔽群消息", Toast.LENGTH_LONG).show();
                                }
                            });
                            return;
                        }
//                        EMClient.getInstance().groupManager().unblockGroupMessage(groupId);
                        canceltoggleBlockGroup(groupId+"@1");
                        runOnUiThread(new Runnable() {
                            public void run() {
                            	Toast.makeText(getApplicationContext(), "打开群消息提醒成功", Toast.LENGTH_LONG).show();
                            	iv_switch_block_groupmsg.setVisibility(View.INVISIBLE);
                            	iv_switch_unblock_groupmsg.setVisibility(View.VISIBLE);
                                progressDialog.dismiss();
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(new Runnable() {
                            public void run() {
                                progressDialog.dismiss();
                                Toast.makeText(getApplicationContext(), st9, Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                }
            }).start();
        }
    }

    /**
     * 群组成员gridadapter
     *
     * @author admin_new
     */
    private class GridAdapter extends ArrayAdapter<ContactGroup> {
    	
//    	private HashMap<Integer, View> viewMap; 

        private int res;
        
        private List<ContactGroup> objects;
        Context context;

        public GridAdapter(Context context, int textViewResourceId, List<ContactGroup> objects) {
            super(context, textViewResourceId, objects);
            this.objects = objects;
            res = textViewResourceId;
            isInDeleteMode = false;
            this.context = context;
//            viewMap = new HashMap<Integer, View>();
        }

        @Override
        public View getView(final int position, View convertView, final ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
//            if(!viewMap.containsKey(position) || viewMap.get(position) == null){ 
                holder = new ViewHolder();
                convertView = LayoutInflater.from(getContext()).inflate(res, null);
                holder.imageView = (ImageView) convertView.findViewById(R.id.iv_avatar);
                holder.textView = (TextView) convertView.findViewById(R.id.tv_name);
                holder.badgeDeleteView = (ImageView) convertView.findViewById(R.id.badge_delete);
                convertView.setTag(holder);
//                viewMap.put(position, convertView);
            } else {
//            	convertView = viewMap.get(position);  
                holder = (ViewHolder) convertView.getTag();
            }
            
//            if(viewMap.size() > 20){  
//                synchronized (convertView) {  
//                    for(int i = 1;i < userGridview.getFirstVisiblePosition() - 3;i ++){  
//                        viewMap.remove(i);  
//                    }  
//                    for(int i = userGridview.getLastVisiblePosition() + 3;i < getCount();i ++){  
//                        viewMap.remove(i);  
//                    }  
//                }  
//            }  
            
            final LinearLayout button = (LinearLayout) convertView.findViewById(R.id.button_avatar);
//            holder.imageView.setImageResource(R.drawable.empty_photo4);//不能设置
//            Logger.i("position------>" + position + " count:" + getCount());
            // 最后一个item，减人按钮
            if (position == getCount() - 1) {
                holder.textView.setText("");
                // 设置成删除按钮
                holder.imageView.setImageResource(R.drawable.em_smiley_minus_btn);
//				button.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.smiley_minus_btn, 0, 0);
                // 如果不是创建者或者没有相应权限，不提供加减人按钮
//                if (!OwnerUid.equals(CurrentUid)) {
//                    // if current user is not group admin, hide add/remove btn
//                    convertView.setVisibility(View.INVISIBLE);
//                } else { // 显示删除按钮
                    if (isInDeleteMode) {
                        // 正处于删除模式下，隐藏删除按钮
                        convertView.setVisibility(View.INVISIBLE);
                    } else {
                        // 正常模式
                        convertView.setVisibility(View.VISIBLE);
                        convertView.findViewById(R.id.badge_delete).setVisibility(View.INVISIBLE);
                    }
                    final String st10 = getResources().getString(R.string.The_delete_button_is_clicked);
//                }
            } else if (position == getCount() - 2) { // 添加群组成员按钮
                holder.textView.setText("");
                if (isInDeleteMode)
                	holder.imageView.setImageResource(R.drawable.em_smiley_cancel_btn);
                else
                holder.imageView.setImageResource(R.drawable.em_smiley_add_btn);
//				button.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.smiley_add_btn, 0, 0);
//                // 如果不是创建者或者没有相应权限
//                if ( !OwnerUid.equals(CurrentUid)) {//!group.isAllowInvites() &&
//                    // if current user is not group admin, hide add/remove btn
//                    convertView.setVisibility(View.INVISIBLE);
//                } else {
                    // 正处于删除模式下,隐藏添加按钮
                    if (isInDeleteMode) {
//                        convertView.setVisibility(View.INVISIBLE);
                    	convertView.setVisibility(View.VISIBLE);
                    } else {
                        convertView.setVisibility(View.VISIBLE);
                        convertView.findViewById(R.id.badge_delete).setVisibility(View.INVISIBLE);
                    }
                    final String st11 = getResources().getString(R.string.Add_a_button_was_clicked);
//                }
            } else{ // 普通item，显示群组成员
            	
//                Logger.i("-------->position:" + position);
                ContactGroup username = getItem(position);
                convertView.setVisibility(View.VISIBLE);
                button.setVisibility(View.VISIBLE);
//				Drawable avatar = getResources().getDrawable(R.drawable.default_avatar);
//				avatar.setBounds(0, 0, referenceWidth, referenceHeight);
//				button.setCompoundDrawables(null, avatar, null, null);
//                EaseUserUtils.setUserNick(username.getUser_name(), holder.textView);
//                EaseUserUtils.setUserAvatar(getContext(), username.getAvatar(), holder.imageView);
//                holder.textView.setText(username.getUsername());
                holder.textView.setText(username.getName());
                String s1 = username.getAvatarPath();
//                int idx = s1.indexOf("./");
//    			if(idx!=-1){
//    				System.out.println(s1.substring(idx+1));
//    				ImageLoader.getInstance().displayImage("http://10.0.2.2/javacenterhome"+s1.substring(idx+1), holder.imageView);
//    			}
                int idx = s1.indexOf("/data/avatar/");
        		String path = "";
        		if(idx!=-1){
        			path = s1.substring(idx+1);
        		}
        		Log.e("================2017 GroupDetailsActivity.java ================", "url======"+XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+s1);
        	    if(s1!=null
        	    		&& s1.length()!=0
        	    		&& !s1.equalsIgnoreCase("null"))
//        	    	ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+s1, holder.imageView,SpiceApplication.getInstance().options);
        	    	ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix+s1, holder.imageView,SpiceApplication.getInstance().options);
        	    else
        	    	holder.imageView.setImageResource(R.drawable.empty_photo4);
//                ImageLoader.getInstance().displayImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+s1, holder.imageView);
//        		mImageFetcher.loadNormalImage(XmppConnectionAdapter.downloadPrefix.replace("/javacenterhome/","/")+s1, holder.imageView,0,0,0,null);
        		if (isInDeleteMode) {
                    // 如果是删除模式下，显示减人图标
                    convertView.findViewById(R.id.badge_delete).setVisibility(View.VISIBLE);
                } else {
                    convertView.findViewById(R.id.badge_delete).setVisibility(View.INVISIBLE);
                }
                
                final String st15 = getResources().getString(R.string.confirm_the_members);

//                holder.imageView.setOnLongClickListener(new OnLongClickListener() {
//
//                    @Override
//                    public boolean onLongClick(View v) {
//                    	if (position<memberItems.size()) {
//                    		if (CurrentUid.equals(username.getUid()))
//                                return true;
//                            if (OwnerUid.equals(CurrentUid)) {
////                                new EaseAlertDialog(GroupDetailsActivity.this, null, st15, null, new AlertDialogUser() {
////
////                                    @Override
////                                    public void onResult(boolean confirmed, Bundle bundle) {
////                                        if (confirmed) {
////                                            addUserToBlackList(username.getUser_name());
////                                        }
////                                    }
////                                }, true).show();
//
//                            }
//    					
//    					}
//                        
//                        return false;
//                    }
//                });
            	
            }
            holder.textView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(context, OtherProfileActivity.class);
		        	intent.putExtra("searchkey",getItem(position).getUsername());
		            context.startActivity(intent);
		            finish();
				}
            });
            holder.imageView.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					
					
					final String st12 = getResources().getString(R.string.not_delete_myself);
	                final String st13 = getResources().getString(R.string.Are_removed);
	                final String st14 = getResources().getString(R.string.Delete_failed);
                    if (isInDeleteMode) {
                    	if(position<memberItems.size()){
                        // 如果是删除自己，return
                    	ContactGroup username = getItem(position);
                        if (CurrentUid.equals(username.getUid())) {
//                            new EaseAlertDialog(GroupDetailsActivity.this, st12).show();
                        	showCustomToast(st12);
                            return;
                        }
//                        if (!NetUtils.hasNetwork(getApplicationContext())) {
//                            Toast.makeText(getApplicationContext(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
//                            return;
//                        }
                        deleteMembersFromGroup(username.getUid(),false);
                    	}else{
//                    		showCustomToast("当为删除状态时，单击空白区域，回到正常状态");
	                        isInDeleteMode = false;
	                        notifyDataSetChanged();
                    	}
                    } else {
                    	if (position<memberItems.size()) {//点击某个群用户头像，进入群用户详细信息页面
    						
//    						Bundle bundle=new Bundle();
//    						bundle.putString("uid", memberItems.get(position).getUid());
//    						bundle.putInt("type", 1);
//    						Intent intent=new Intent();
//    						intent.setClass(context, FriendInformationActivity.class);
//    						intent.putExtras(bundle);
//    						context.startActivity(intent);
                    		
                    		Intent intent = new Intent(context, OtherProfileActivity.class);
        		        	intent.putExtra("searchkey",getItem(position).getUsername());
        		            context.startActivity(intent);
    					    finish();
    					}
    					if (position == getCount() -2) {//添加群组成员按钮
    						if(!isInDeleteMode){
    						ArrayList<String> s = new ArrayList<String>();
                            if(allMemberItems != null){
                            	for (int i = 0; i < allMemberItems.size(); i++) {
                        			s.add(allMemberItems.get(i).getUid());
                        		}
                            }
                            startActivityForResult(
                                    (new Intent(GroupDetailsActivity.this, GroupNew2Activity.class).putExtra("groupId", groupId).putExtra("CurrentUid", CurrentUid).putExtra("CurrentName", CurrentName).putExtra("CurrentAvatarpath",CurrentAvatarpath)),
                                    REQUEST_CODE_ADD_USER);
    						}else{
    							 isInDeleteMode = false;
    	                         notifyDataSetChanged();
    						}
    					}
    					
    					if (position == getCount()-1) {

                            isInDeleteMode = true;
                            notifyDataSetChanged();
                        
    					}
                    }
                
				}
			});
//            holder.
            return convertView;
        }

        @Override
        public int getCount() {
            return super.getCount() + 2;
        }
        
        @Override

        public ContactGroup getItem(int position) {

        return super.getItem(position);//获取数据集中与指定索引对应的数据项

        }

         

        @Override

        public long getItemId(int position) {

        return position;//获取在列表中与指定索引对应的行id

        }
    }

//	@Override
//	public void onItemClick(AdapterView<?> parent, View view, int position,
//			long id)
//	{
////		if (isInDeleteMode) {
////			if(position>=memberItems.size()){
////				showCustomToast("当为删除状态时，单击空白区域，回到正常状态");
////                isInDeleteMode = false;
////                this.getAdapter().notifyDataSetChanged();
////			}
////		}
//		Toast.makeText(this, "222当为删除状态时，单击空白区域，回到正常状态", Toast.LENGTH_SHORT).show();
//	}
	
    protected void deleteMembersFromGroup(final String username,final boolean isExit) {
        final String st13 = getResources().getString(R.string.Are_removed);
        final String st14 = getResources().getString(R.string.Delete_failed);
        final ProgressDialog deleteDialog = new ProgressDialog(GroupDetailsActivity.this);
        deleteDialog.setMessage(st13);
        deleteDialog.setCanceledOnTouchOutside(false);
        deleteDialog.show();
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    // 删除被选中的成员
//                    Logger.i("userName:" + username);
//                    EMClient.getInstance().groupManager().removeUserFromGroup(groupId, username);
                	initExitGroup(groupId, username);
                	if(isExit){
                		finish();
                	}else{
	                    isInDeleteMode = false;
	                    runOnUiThread(new Runnable() {
	
	                        @Override
	                        public void run() {
	                            deleteDialog.dismiss();
	//                            refreshMembers(group);
	                            getGroupMembers(groupId);
	                            setTitle(groupName + "("
	                                    + AffiliationsCount + st);
	                        }
	                    });
                	}
                } catch (final Exception e) {
                    deleteDialog.dismiss();
                    runOnUiThread(new Runnable() {
                        public void run() {
                            Toast.makeText(getApplicationContext(), st14 + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }

            }
        }).start();
    }
    private boolean initExitGroup(String tagid,String uids){//page=1 keystr=""
//    	showCustomToast("initGeGroupMembers1");
    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers1111++++++++++++++");
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
				Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers2222++++++++++++++");
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers3333++++++++++++++");
		    	    ExitGroupIQ reqXML = new ExitGroupIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
		            CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		            CurrentName = mXmppFacade.getXmppConnectionAdapter().getName();
		            CurrentAvatarpath = mXmppFacade.getXmppConnectionAdapter().getAvatarpath();
		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		    	    CurrentUsername = username;
//		            reqXML.setUsername(username);
		    	    reqXML.setUids(uids);
		            reqXML.setTagid(tagid);
		            reqXML.setOwnerid(OwnerUid);
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
		            reqXML.setUuid(uuid);
	//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid+tagid+OwnerUid;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "exitgroupiq"; 
		    		String namespace = "com:isharemessage:exitgroupiq";
		    		ExitGroupIQResponseProvider provider = new ExitGroupIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "exitgroupiq", "com:isharemessage:exitgroupiq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof ExitGroupIQResponse) {
		                	final ExitGroupIQResponse exitGroupIQResponse = (ExitGroupIQResponse) rt;
	
		                    if (exitGroupIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:exitgroupiq")) {
	//	    					MainActivity.this.runOnUiThread(new Runnable() {
	//		                    	
	//    							@Override
	//    							public void run() {
	//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
	//    							}
	//    						});
		                        String Id = exitGroupIQResponse.getId();
		                        String Apikey = exitGroupIQResponse.getApikey();
		                        
		                        String retcode = exitGroupIQResponse.getRetcode();
		                        String memo = exitGroupIQResponse.getMemo();
		                        if(retcode.equalsIgnoreCase("0000")){
		                        	errorType = 0;
		                        	return true;
		                        }
		                        else if(retcode.equalsIgnoreCase("0002"))
		                        	errorType = 6;
		                        else
		                        	errorType = 5;
		                        
		                    }
		                } 
		            }
		    		errorType = 1;

		    }else
		    	errorType = 1;
		    
			}else
				errorType = 4;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
		}
		return false;
    }
    

    private boolean initDisMissGroup(String tagid){//page=1 keystr=""
//    	showCustomToast("initGeGroupMembers1");
    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers1111++++++++++++++");
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
				Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers2222++++++++++++++");
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers3333++++++++++++++");
		    	    dismissGroupIQ reqXML = new dismissGroupIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
		            CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		            CurrentName = mXmppFacade.getXmppConnectionAdapter().getName();
		            CurrentAvatarpath = mXmppFacade.getXmppConnectionAdapter().getAvatarpath();
		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		    	    CurrentUsername = username;
//		            reqXML.setUsername(username);
		            reqXML.setTagid(tagid);
		            reqXML.setOwnerid(OwnerUid);
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
		            reqXML.setUuid(uuid);
	//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid+tagid+OwnerUid;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "dismissgroupiq"; 
		    		String namespace = "com:isharemessage:dismissgroupiq";
		    		dismissGroupIQResponseProvider provider = new dismissGroupIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "dismissgroupiq", "com:isharemessage:dismissgroupiq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof dismissGroupIQResponse) {
		                	final dismissGroupIQResponse dmissGroupIQResponse = (dismissGroupIQResponse) rt;
	
		                    if (dmissGroupIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:dismissgroupiq")) {
	//	    					MainActivity.this.runOnUiThread(new Runnable() {
	//		                    	
	//    							@Override
	//    							public void run() {
	//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
	//    							}
	//    						});
		                        String Id = dmissGroupIQResponse.getId();
		                        String Apikey = dmissGroupIQResponse.getApikey();
		                        
		                        String retcode = dmissGroupIQResponse.getRetcode();
		                        String memo = dmissGroupIQResponse.getMemo();
		                        if(retcode.equalsIgnoreCase("0000")){
		                        	errorType = 0;
		                        	return true;
		                        }
		                        else if(retcode.equalsIgnoreCase("0002"))
		                        	errorType = 6;
		                        else
		                        	errorType = 5;
		                        
		                    }
		                } 
		            }
		    		errorType = 1;

		    }else
		    	errorType = 1;
		    
			}else
				errorType = 4;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
		}
		return false;
    }
    
	private void startUpdateGroup(final String tagid,final String groupName,final String pic) {

		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
//				showLoadingDialog("正在加载,请稍后...");
			}

			@Override
			protected Boolean doInBackground(Void... params) {
//				initContactList();
				initUpdateGroup(tagid,groupName,pic);
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);
//				dismissLoadingDialog();
//				if (!result) {
////					showCustomToast("数据加载失败...");
					mHandler.sendEmptyMessage(5);
//				} else {
//					mHandler.sendEmptyMessage(11);
//				}
//				ptrstgv.getRefreshableView().hideFooterView();
			}

		});
	}
	
    private boolean initUpdateGroup(String tagid,String groupName,String pic){//page=1 keystr=""
//    	showCustomToast("initGeGroupMembers1");
    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers1111++++++++++++++");
		try{
			if(BeemConnectivity.isConnected(getApplicationContext())){
				Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers2222++++++++++++++");
		    if(mXmppFacade!=null 
					&& mXmppFacade.getXmppConnectionAdapter()!=null 
					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//					&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAlive()
					){
		    	Log.e("================GroupDetailsActivity.java ================", "++++++++++++++initGeGroupMembers3333++++++++++++++");
		    	    UpdateGroupIQ reqXML = new UpdateGroupIQ();
		            reqXML.setId("1234567890");
		            reqXML.setApikey("abcdefghijklmnopqrstuvwxyz");
		            reqXML.setUid(StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID()));//2
		            CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		            CurrentName = mXmppFacade.getXmppConnectionAdapter().getName();
		            CurrentAvatarpath = mXmppFacade.getXmppConnectionAdapter().getAvatarpath();
		            SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
		    	    String username = settings.getString(BeemApplication.ACCOUNT_USERNAME_KEY, "");
		    	    CurrentUsername = username;
//		            reqXML.setUsername(username);
		            reqXML.setTagid(tagid);
		            reqXML.setOwnerid(OwnerUid);
		            reqXML.setGroupname(groupName);
		            reqXML.setPic(pic);
		            String uuid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().getUUID(this,username);
		            reqXML.setUuid(uuid);
	//	            String hashcode = "";//apikey+view+orderby+uuid 使用登录成功后返回的sessionid作为密码做3des运算
		            String hash_dest_src = "abcdefghijklmnopqrstuvwxyz"+ StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID())+uuid+tagid+OwnerUid;
		            String hash_dest = EncryptionUtil.getHash2(hash_dest_src, "SHA");
		            reqXML.setHashcode(hash_dest);
		            reqXML.setType(IQ.Type.SET);
		            String elementName = "updategroupiq"; 
		    		String namespace = "com:isharemessage:updategroupiq";
		    		UpdateGroupIQResponseProvider provider = new UpdateGroupIQResponseProvider();
		            Packet rt =  mXmppFacade.getXmppConnectionAdapter().excute(reqXML, "updategroupiq", "com:isharemessage:updategroupiq", provider);
		            
		            if(rt!=null){
		                if (rt instanceof UpdateGroupIQResponse) {
		                	final UpdateGroupIQResponse updateGroupIQResponse = (UpdateGroupIQResponse) rt;
	
		                    if (updateGroupIQResponse.getChildElementXML().contains(
		                            "com:isharemessage:updategroupiq")) {
	//	    					MainActivity.this.runOnUiThread(new Runnable() {
	//		                    	
	//    							@Override
	//    							public void run() {
	//    								showCustomToast("服务器应答消息："+contactGroupListIQResponse.toXML().toString());
	//    							}
	//    						});
		                        String Id = updateGroupIQResponse.getId();
		                        String Apikey = updateGroupIQResponse.getApikey();
		                        
		                        String retcode = updateGroupIQResponse.getRetcode();
		                        String memo = updateGroupIQResponse.getMemo();
		                        if(retcode.equalsIgnoreCase("0000")){
		                        	errorType = 0;
		                        	return true;
		                        }
		                        else if(retcode.equalsIgnoreCase("0002"))
		                        	errorType = 6;
		                        else
		                        	errorType = 5;
		                        
		                    }
		                } 
		            }
		    		errorType = 1;

		    }else
		    	errorType = 1;
		    
			}else
				errorType = 4;
		}catch(RemoteException e){
			e.printStackTrace();
			errorType = 2;
		}catch(Exception e){
			e.printStackTrace();
			errorType = 3;
		}
		return false;
    }
//    protected void updateGroup() {
//        new Thread(new Runnable() {
//            public void run() {
//                try {
//                    final EMGroup returnGroup = EMClient.getInstance().groupManager().getGroupFromServer(groupId);
//                    
//                    
//
//                    runOnUiThread(new Runnable() {
//                        public void run() {
//                            setTitle(group.getGroupName() + "(" + returnGroup.getAffiliationsCount()
//                                    + ")");
//                            num.setText(returnGroup.getAffiliationsCount()+"/"+returnGroup.getMemberCount());
//                            //loadingPB.setVisibility(View.INVISIBLE);
//                            refreshMembers(returnGroup);
//
//                            // update block
//                            if (group.isMsgBlocked()) {
//                            	
//                            	iv_switch_block_groupmsg.setVisibility(View.VISIBLE);
//                            	iv_switch_unblock_groupmsg.setVisibility(View.INVISIBLE);
//                            } else {
//                            	iv_switch_block_groupmsg.setVisibility(View.INVISIBLE);
//                            	iv_switch_unblock_groupmsg.setVisibility(View.VISIBLE);
//                            }
//                        }
//                    });
//                    GroupMemberDao groupMemberDao = new GroupMemberDao(GroupDetailsActivity.this);
//                	groupMemberDao.saveGroup(returnGroup.getMembers(),groupId);
//                	// 更新本地数据
//                    EMClient.getInstance().groupManager().getGroupFromServer(returnGroup.getGroupId());
//                } catch (Exception e) {
//                    runOnUiThread(new Runnable() {
//                        public void run() {
//                            //loadingPB.setVisibility(View.INVISIBLE);
//                        }
//                    });
//                }
//            }
//        }).start();
//    }

    public void back(View view) {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        instance = null;
//        mImageFetcher.onCancel();
        clearAsyncTask();
	    try{//网络状态相关
		    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
		    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
	    }catch (RemoteException e) {
	    	e.printStackTrace();
	    }
        if (mBinded) {
			getApplicationContext().unbindService(mServConn);
		    mBinded = false;
		}
		mXmppFacade = null;
		//网络状态start
		unregisterReceiver(mNetWorkReceiver); // 删除广播
		if(tm!=null){
			tm.listen(myPhoneCallListener,PhoneStateListener.LISTEN_NONE);//取消监听即可
			tm = null;
		}
		if(myPhoneCallListener!=null)
			myPhoneCallListener = null;
		//网络状态end
    }

    private static class ViewHolder {
        ImageView imageView;
        TextView textView;
        ImageView badgeDeleteView;
    }

//    /**
//     * 监测群组解散或者被T事件
//     */
//    private class GroupRemoveListener extends EaseGroupRemoveListener {
//
//        @Override
//        public void onUserRemoved(final String groupId, String groupName) {
//            finish();
//        }
//
//        @Override
//        public void onGroupDestroyed(String s, String s1) {
//            finish();
//        }
//
//        @Override
//        public void onAutoAcceptInvitationFromGroup(String s, String s1, String s2) {
//
//        }
//
//    }
    
    
    /**
     * The service connection used to connect to the Beem service.
     */
    private class BeemServiceConnection implements ServiceConnection {
		/**
		 * Constructor.
		 */
		public BeemServiceConnection() {
		}
	
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
		    mXmppFacade = IXmppFacade.Stub.asInterface(service);
		    if(mXmppFacade!=null){
		    	mBinded = true;//20130804 added by allen
		    	try{
		    		mXmppFacade.getXmppConnectionAdapter().registerConnectionStatusCallback(GroupDetailsActivity.this);//网络状态相关
		    	    CurrentUid = StringUtils.parseBareAddress2(mXmppFacade.getXmppConnectionAdapter().getJID());
		    	}catch(Exception e){}
		    getGroupMembers(groupId);
		    }
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
			 try{//网络状态相关
				    if(mXmppFacade!=null && mXmppFacade.getXmppConnectionAdapter()!=null)
				    	mXmppFacade.getXmppConnectionAdapter().unRegisterConnectionStatusCallback();
			    }catch (RemoteException e) {
			    	e.printStackTrace();
			    }
		    mXmppFacade = null;
		    mBinded = false;
		}
    }

	/** 显示自定义Toast提示(来自String) **/
	protected void showCustomToast(String text) {
		View toastRoot = LayoutInflater.from(GroupDetailsActivity.this).inflate(
				R.layout.common_toast, null);
		((HandyTextView) toastRoot.findViewById(R.id.toast_text)).setText(text);
		Toast toast = new Toast(GroupDetailsActivity.this);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(toastRoot);
		toast.show();
	}
	
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
	
		@Override
		public void onClick() {
//			getContactList(ConstantValues.refresh);
//			startActivity(new Intent(OtherProfileActivity.this, ContactFrameActivity.class));//ContactListPullRefListActivity
			Intent intent =  new Intent(GroupDetailsActivity.this, ContactFrameActivity.class);
	    	intent.putExtra("refreshroster", "truezhiding");
			startActivity(intent);
			GroupDetailsActivity.this.finish();
		}
	}
	
	//网络状态 start
		@Override
		public void connectionStatusChanged(int connectedState, String reason) {
			Log.e("MMMMM20140604MMMMMMMMMMMM", "++++++++++++++connectionStatusChanged0++++++++++++");
			switch (connectedState) {
			case 0://connectionClosed
				mHandler3.sendEmptyMessage(0);
				break;
			case 1://connectionClosedOnError
//				mConnectErrorView.setVisibility(View.VISIBLE);
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("连接异常!");
				mHandler3.sendEmptyMessage(1);
				break;
			case 2://reconnectingIn
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("连接中...");
				mHandler3.sendEmptyMessage(2);
				break;
			case 3://reconnectionFailed
//				mNetErrorView.setVisibility(View.VISIBLE);
//				mConnect_status_info.setText("重连失败!");
				mHandler3.sendEmptyMessage(3);
				break;
			case 4://reconnectionSuccessful
//				mNetErrorView.setVisibility(View.GONE);
				mHandler3.sendEmptyMessage(4);

			default:
				break;
			}
		}
		Handler mHandler3 = new Handler() {

			@Override
			public void handleMessage(android.os.Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case 0:
					break;

				case 1:
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("连接异常!");
					break;

				case 2:
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("连接中...");
					break;
				case 3:
					mNetErrorView.setVisibility(View.VISIBLE);
					if(BeemConnectivity.isConnected(mContext))
					mConnect_status_info.setText("重连失败!");
					break;
					
				case 4:
					mNetErrorView.setVisibility(View.GONE);
					String udid = "";
					String partnerid = "";
					try{
						udid = mXmppFacade.getXmppConnectionAdapter().getAdaptee().UDID;
						partnerid = mXmppFacade.getXmppConnectionAdapter().getMService().getPartnerid();
					}catch(Exception e){
						e.printStackTrace();
					}
//					udidTextView.setText("udid="+udid);
//					partneridEditText.setText(partnerid);
//					getContactList();//20141025 added by allen
					break;
				case 5:
					mNetErrorView.setVisibility(View.VISIBLE);
					mConnect_status_info.setText("当前网络不可用，请检查你的网络设置。");
					break;
				case 6:
					if(mXmppFacade!=null 
//							&& mXmppFacade.getXmppConnectionAdapter()!=null 
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee()!=null//&& !mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isConnected()
//							&& mXmppFacade.getXmppConnectionAdapter().getAdaptee().isAuthenticated()
							&& BeemConnectivity.isConnected(mContext)){
						
					}else{
						mNetErrorView.setVisibility(View.VISIBLE);
						if(BeemConnectivity.isConnected(mContext))
						mConnect_status_info.setText("网络可用,连接中...");
					}
					break;	
				}
			}

		};
		private BroadcastReceiver mNetWorkReceiver = new BroadcastReceiver() {
	        @Override
	        public void onReceive(Context context, Intent intent) {
	            String action = intent.getAction();  
	            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {  
	                Log.d("PoupWindowContactList", "网络状态已经改变");  
//	                connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);  
//	                info = connectivityManager.getActiveNetworkInfo();    
//	                if(info != null && info.isAvailable()) {  
//	                    String name = info.getTypeName();  
//	                    Log.d(tag, "当前网络名称：" + name);  
//	                    //doSomething()  
//	                } else {  
//	                    Log.d(tag, "没有可用网络");  
//	                  //doSomething()  
//	                }  
	                if(BeemConnectivity.isConnected(context)){
//	                	mNetErrorView.setVisibility(View.GONE);
//	                	isconnect = 0;
	                	mHandler3.sendEmptyMessage(6);//4
	                }else{
//	                	mNetErrorView.setVisibility(View.VISIBLE);
//	                	isconnect = 1;
	                	mHandler3.sendEmptyMessage(5);
	                	Log.d("PoupWindowContactList", "当前网络不可用，请检查你的网络设置。");
	                }
	            } 
	        }
		};
		
		private boolean phonestate = false;//false其他， true接起电话或电话进行时 
	    /* 内部class继承PhoneStateListener */
	    public class exPhoneCallListener extends PhoneStateListener
	    {
	        /* 重写onCallStateChanged
	        当状态改变时改变myTextView1的文字及颜色 */
	        public void onCallStateChanged(int state, String incomingNumber)
	        {
	          switch (state)
	          {
	            /* 无任何状态时 :说明没有拨打电话的界面的时候，也就是在拨打电话前和挂电话后的情况*/
	            case TelephonyManager.CALL_STATE_IDLE:
	            	Log.e("================20131216 无任何电话状态时================", "无任何电话状态时");
	            	if(phonestate){
	            		onPhoneStateResume();
	            	}
	            	phonestate = false;
	              break;
	            /* 接起电话时 :至少有一个电话存在、拨出或激活、接听，而没有一个电话在通话或等待的状态*/
	            case TelephonyManager.CALL_STATE_OFFHOOK:
	            	Log.e("================20131216 接起电话时================", "接起电话时");
	            	onPhoneStatePause();
	            	phonestate = true;
	              break;
	            /* 电话进来时 :在通话的过程中*/
	            case TelephonyManager.CALL_STATE_RINGING:
//	              getContactPeople(incomingNumber);
	            	Log.e("================20131216 电话进来时================", "电话进来时");
//	            	onBackPressed();
	            	onPhoneStatePause();
	            	phonestate = true;
	              break;
	            default:
	              break;
	          }
	          super.onCallStateChanged(state, incomingNumber);
	        }
	    }
	    
	    protected void onPhoneStatePause() {
//			super.onPause();
	    	try{
//	    		try {
//	    		    if (mRoster != null) {
//	    			mRoster.removeRosterListener(mBeemRosterListener);
//	    			mRoster = null;
//	    		    }
//	    		} catch (RemoteException e) {
//	    		    Log.d("ContactList", "Remote exception", e);
//	    		}
				if (mBinded) {
					getApplicationContext().unbindService(mServConn);
				    mBinded = false;
				}
				mXmppFacade = null;
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	    }
	    
	    protected void onPhoneStateResume() {
//			super.onResume();
	    	try{
			if (!mBinded){
//			    new Thread()
//			    {
//			        @Override
//			        public void run()
//			        {
			    mBinded = getApplicationContext().bindService(SERVICE_INTENT, mServConn, BIND_AUTO_CREATE);

//			        }
//			    }.start();		    
			}
			if (mBinded){
//				mImageFetcher.setExitTasksEarly(false);
			}
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	    }
	    
	    /*
	     * 打开设置网络界面
	     * */
	    public static void setNetworkMethod(final Context context){
	        //提示对话框
	        AlertDialog.Builder builder=new AlertDialog.Builder(context);
	        builder.setTitle("网络设置提示").setMessage("网络连接不可用,是否进行设置?").setPositiveButton("设置", new DialogInterface.OnClickListener() {
	            
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	                // TODO Auto-generated method stub
	                Intent intent=null;
	                //判断手机系统的版本  即API大于10 就是3.0或以上版本 
	                if(android.os.Build.VERSION.SDK_INT>10){
	                    intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
	                }else{
	                    intent = new Intent();
	                    ComponentName component = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
	                    intent.setComponent(component);
	                    intent.setAction("android.intent.action.VIEW");
	                }
	                context.startActivity(intent);
	            }
	        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
	            
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	                // TODO Auto-generated method stub
	                dialog.dismiss();
	            }
	        }).show();
	    }
		//网络状态 end
}
